var iTime = 0;
var isChatScroll = false;
var isRequested = false;
var iTimeout;
function deleteMessageChat(){
	jQuery('#chat_story').html('');
	/*jQuery.ajax ({
		type : 'POST',
		url : '/receive_message',
		dataType: 'json',
		data : {action:'delete_all'},
		success : function(data) {
			
		},
		error: function(jqXHR, textStatus, errorThrown){}
	});*/
}
function sendMessageChat(){
	var message = jQuery('#msg_box').val();
	jQuery('#msg_box').val('');
	isChatScroll = false;
	jQuery.ajax ({
		type : 'POST',
		url : '/receive_message',
		dataType: 'json',
		data : {message:message, time:iTime, action:'send_message'},
		success : function(data) {
			getMessageChat();
		},
		error: function(jqXHR, textStatus, errorThrown){
			alert('Network error');
			window.location.reload();
		}
	});
}
function getMessageChat(){
	if(isRequested == false)
	{
		isRequested = true;
		jQuery.ajax ({
			type : 'POST',
			url : '/receive_message',
			dataType: 'json',
			data : {time:iTime, action:'get_message'},
			success : function(data) {
				if(data._iCode == 1)
				{
					for(i in data._vChatLog)
					{
						var isEmpty = jQuery('#chat_story').html();
						if(isEmpty == '')
							jQuery('#chat_story').html(isEmpty + data._vChatLog[i]._sUserName + ': ' + data._vChatLog[i]._sMessage);
						else
							jQuery('#chat_story').html(isEmpty + '<br/>' + data._vChatLog[i]._sUserName + ': ' + data._vChatLog[i]._sMessage);
					}
					if(isChatScroll == false)
					{
						jQuery('#chat_story').animate({ scrollTop: jQuery('#chat_story').prop("scrollHeight") }, "slow", function(){
							isChatScroll = false;	
						});
					}
					iTime = data._lTime;
				}
				
				isRequested = false;
				//iTimeout = setTimeout(getMessageChat, 3000);
			},
			error: function(jqXHR, textStatus, errorThrown){
				alert('Network error');
				window.location.reload();
			}
		});
	}
}
jQuery(document).ready(function() {
	getMessageChat();
	setInterval(getMessageChat, 3000);
	jQuery('#msg_box').keyup(function (e){
		if(e.keyCode == 13)
		{
			sendMessageChat();
		}
	});
	jQuery('#chat_story').scroll(function(){
		isChatScroll = true;
	});
});